function formatInt(num) {
  return Math.ceil(num * 100) / 100;
}

const state = {
  cartProducts: JSON.parse(window.localStorage.getItem('cart-products')) || []
}
const getters = {
  totalCount(state) {
    return state.cartProducts.reduce((sum, prod) => {
      return formatInt(sum + prod.count)
    }, 0)
  },
  totalPrice(state) {
    return state.cartProducts.reduce((sum, prod) => {
      return formatInt(sum + prod.totalPrice)
    }, 0)
  },
  checkedCount(state) {
    return state.cartProducts.reduce((sum, prod) => {
      if (prod.isChecked) {
        sum += prod.count
      }
      return formatInt(sum)
    }, 0)
  },
  checkedPrice(state) {
    return state.cartProducts.reduce((sum, prod) => {
      if (prod.isChecked) {
        sum += prod.totalPrice
      }
      return formatInt(sum)
    }, 0)
  }
}
const mutations = {
  // 添加事件
  addToCart(state, product) {
    const prod = state.cartProducts.find(item => item.id === product.id)
    if (prod) {
      prod.count++
      prod.isChecked = true
      prod.totalPrice = prod.count * prod.price
    } else {
      state.cartProducts.push({
        ...product,
        count: 1,
        isChecked: true,
        totalPrice: product.price
      })
    }
  },

  // 删除事件
  deleteFromCart(state, prodId) {
    const index = state.cartProducts.findIndex(item => item.id === prodId)
    index !== -1 && state.cartProducts.splice(index, 1)
  },

  // 全选事件
  updateAllProductChecked(state, checked) {
    state.cartProducts.forEach(prod => {
      prod.isChecked = checked
    })
  },

  // 选择事件
  updateProductChecked(state, { checked, prodId }) {
    const prod = state.cartProducts.find(prod => prod.id === prodId)
    prod && (prod.isChecked = checked)
  },

  // 更新数据
  updateProduct(state, { prodId, count }) {
    const prod = state.cartProducts.find(prod => prod.id === prodId)
    if (prod) {
      prod.count = count
      prod.totalPrice = formatInt(count * prod.price)
    }
  }
}

const actions = {}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
